package com.xiaoyang.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    private JacksonUtil() {
    }
    /**
     * 静态代码块单例
     */
    private final static ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    private static <T > T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    private static <T > T tryParse(Callable<T> parser, Class<? extends
            Exception> check){
        try {
            return parser.call();
        } catch (Exception ex) {
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }

    /**
     * 反序列化
     *
     * @param content
     * @param valueType
     * @return
     * @param <T>
     */
    public static <T > T readValue(String content, Class<T> valueType) {
        return JacksonUtil.tryParse(()->
                JacksonUtil.getObjectMapper().readValue(content, valueType));
    }

    /**
     * 反序列化list
     *
     * @param content
     * @param parameterClasses
     * @return
     * @param <T>
     */
    public static <T > T readListValue(String content, Class<?>
            parameterClasses) {
        return JacksonUtil.tryParse(()->
                JacksonUtil.getObjectMapper().readValue(content,
                        JacksonUtil.getObjectMapper()
                                .getTypeFactory()
                                .constructParametricType(List.class,
                                        parameterClasses)));
    }

    /**
     * 序列化
     *
     * @param value
     * @return
     */
    public static String writeValueAsString(Object value) {
        return JacksonUtil.tryParse(()->
                JacksonUtil.getObjectMapper().writeValueAsString(value));
    }
}
